Using Python Packages
This lesson gives a brief overview of Python packages.
We'll cover the following
Importing packages#
Python allows developers to group related functions into hierarchical namespaces like packages, modules, etc.
When we want to use a module, class, or function from a package, we need to import it. There are many different ways to import packages. The most basic syntax is:
import numpy
after which any relevant module, class or function in that package inside numpy can be called as numpy.function().
Some packages also have sub-packages with specialized functions. For example, the numpy package has a subpackage called random, which has a bunch of functions that deal with random variables.
numpy also has a sub-package linalg, which has a bunch of functions for linear algebra.
Aliasing#
If you don’t like the name of the package, for example, because it is long, you can change the name. The numpy package is renamed to np by typing
import numpy as np
after which all functions in numpy can be called as np.function().
If the numpy package is imported with import numpy as np, functions in the random subpackage can be called as np.random.function().
Importing specific functions#
If you only need one specific function, you don’t have to import the entire package. For example, if you only want the cosine function of the numpy package, you may import it as:
from numpy import cos
after which you can simply call the cosine function as cos(). You can even rename functions of the package when you import them using the as alias pointing to that function. For example, after:
from numpy import cos as newname
you can call the function newname() to compute the cosine.
In this course we always import
numpyand call itnpand importmatplotlib.pyplotand call itpltsince both are standard names in the Python community.
We will learn more about packages in Python as we progress along this course.
Let’s test your knowledge with a quiz in the next lesson.
Tuples and Dictionaries
Quiz 1!